const http = require('http')
const fs = require('fs')
const nunjucks = require('./nunjucks')

const server = http.createServer()

let users = [
    { id: 1, username: '大海' },
    { id: 2, username: '子鼠' },
    { id: 3, username: '小蕊' },
]
// const items = require('./data/items.json');

// 路由表
const routesMap = new Map()
routesMap.set('/', async (req, res) => {
    res.setHeader('Content-Type', 'text/html;charset="utf-8"')
    res.end('首页')
})
routesMap.set('/list', async (req, res) => {
    res.setHeader('Content-Type', 'text/html;charset="utf-8"')
    //   res.end(`
    //     <ul>
    //       ${users.map(u => {
    //       return `<li>${u.username}</li>`
    //   }).join('')}
    //     </ul>
    // `);
    //   let tplData = {}
    //   tplData.users  = users.map(u => {
    //     return `<li>${u.username}</li>`
    //   }).join('');

    // console.log(dataString);
    // let tpl = fs.readFileSync('./template/list.tpl.html').toString();
    // tpl = tpl.replace(/\{\{(\w+)\}\}/gi, ( $0, $1 ) => {
    //     // console.log($1);
    //     return tplData[$1];
    // })

    // let str = '<h1>{{title}}</h1>';
    // let tpl = nunjucks.renderString(str, {
    //     title: '开课吧'
    // });

    let tpl = fs.readFileSync('./template/list.html').toString()
    res.end(nunjucks.renderString(tpl, {
        users
    }))
})

server.on('request', async (req, res) => {
    let url = req.url

    if (url.startsWith('/public')) {
        let content = fs.readFileSync(`.${url}`).toString()

        res.end(content)
    }

    let routeHandler = routesMap.get(url)
    if (routeHandler) {
        await routeHandler(req, res)
    } else {
        res.statusCode = 302
        res.setHeader('Location', '/')
        res.end()
    }

})

server.listen(8888, '0.0.0.0', () => {
    console.log(`服务启动成功`)
})
